package com.css.common.security.interceptor;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.css.common.core.constant.SecurityConstants;
import com.css.common.core.context.SecurityContextHolder;
import com.css.common.core.session.SessionManager;
import com.css.common.core.session.SessionUtils;
import com.css.common.core.utils.BaseUtil;
import com.css.common.core.utils.GyUtils;
import com.css.common.core.utils.ServletUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.AsyncHandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 自定义请求头拦截器，将Header数据封装到线程变量中方便获取
 * 注意：此拦截器会同时验证当前用户有效期自动刷新有效期
 *
 * @author css
 */
@Slf4j
public class HeaderInterceptor implements AsyncHandlerInterceptor
{
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
    {
        if (!(handler instanceof HandlerMethod))
        {
            return true;
        }
        //解析用户信息
        String yhxxHash = ServletUtils.getHeader(request, "yhxx");
        if (GyUtils.isNull(yhxxHash)) {
            return true;
        }
        Map<String, Object> yhxx =  JSONUtil.toBean(yhxxHash, Map.class);
        SessionManager.get().setGlzhbz("31".equals(yhxx.get("yhdlsfdm")) ? "Y" : "N");//管理员账号标志：Y是管理
        SessionManager.get().setYhdlzh(BaseUtil.object2Str(yhxx.get("yhdlzh")));//用户登录账号
        SessionManager.get().setQyid(BaseUtil.object2Str(yhxx.get("qyid")));//企业id
        SessionManager.get().setQysh(BaseUtil.object2Str(yhxx.get("qysh")));//企业税号
        SessionManager.get().setQymc(BaseUtil.object2Str(yhxx.get("qymc")));//企业税号
        SessionManager.get().setYhdlsfdm(BaseUtil.object2Str(yhxx.get("yhdlsfdm")));//用户登录身份代码
        SessionManager.get().setZrrid(BaseUtil.object2Str(yhxx.get("zrrid")));//自然人id
        SessionManager.get().setZrrxm(BaseUtil.object2Str(yhxx.get("xm")));//自然人姓名
        SessionManager.get().setZrrzjhm(BaseUtil.object2Str(yhxx.get("sfzjhm")));//自然人证件号码
        SessionManager.get().setZrrsjhm(BaseUtil.object2Str(yhxx.get("sjh")));//自然人手机号码
        try {
            SessionManager.get().setXtqdDm(!BaseUtil.isNull(yhxx.get("xtqdDm"))?Integer.valueOf(yhxx.get("xtqdDm")+""):null);//渠道代码
        }catch (Exception e){
            log.info("获取xtqdDm异常："+e);
        }
        SessionManager.get().setMap(yhxx);
        log.info("session:yhmm:{}", JSON.toJSONString(yhxx));
        log.info("session:zrrid:{}", SessionUtils.getZrrid());

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception
    {
        SessionManager.getClear();
    }
}
